package com.woniu.cq.mallgateway.config;

import com.woniu.cq.mallcommon.common.JwtUntil;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.MediaType;
import org.springframework.http.server.RequestPath;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author Daniel
 * @version 1.0.0
 * @ClassName LoginFilter
 * @Description 过滤器判断token
 * @createTime 2020年09月22日 11:34:00
 */
@Component
public class LoginFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String uri = exchange.getRequest().getURI().getPath();
        if ("/user/login".equals(uri)) {
            return chain.filter(exchange);
        }
        String token = exchange.getRequest().getHeaders().getFirst("X-Token");
        if (StringUtils.isNotEmpty(token)) {
            try {
                JwtUntil.parseToken(token);
                return chain.filter(exchange);
            } catch (Exception e) {
                exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);
                return exchange.getResponse().writeWith(Mono.fromSupplier(()-> exchange.getResponse().bufferFactory().wrap("{\"resp\":\"no login\"}".getBytes())));
            }

        }
        return exchange.getResponse().writeWith(Mono.fromSupplier(()-> exchange.getResponse().bufferFactory().wrap("{\"resp\":\"no login\"}".getBytes())));
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
